java 如何从JMockit模拟静态方法

您所在的位置:网站首页 junit mock数据库 java 如何从JMockit模拟静态方法

java 如何从JMockit模拟静态方法

2023-03-23 07:11| 来源: 网络整理| 查看: 265

还有另一种使用JMockit模拟静态方法的方法(使用Delegate类)。我发现它更方便和优雅。

public class Service { public String addSuffix(String str) { // method to be tested return Utils.staticMethod(str); } }public class Utils { public static String staticMethod(String s) { // method to be mocked String suffix = DatabaseManager.findSuffix("default_suffix"); return s.concat(suffix); } }public class Test { @Tested Service service; @Mocked Utils utils; // @Mocked will make sure all methods will be mocked (including static methods) @Test public void test() { new Expectations() {{ Utils.staticMethod(anyString); times = 1; result = new Delegate() { public String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod return ""; // provide custom implementation for your Utils#staticMethod } } }} service.addSuffix("test_value"); new Verifications() {{ String s; Utils.staticMethod(s = withCapture()); times = 1; assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod }} } }

参考:https://jmockit.github.io/tutorial/Mocking.html#delegateshttps://jmockit.github.io/tutorial/Mocking.html#withCapture



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3